import 'package:flutter/material.dart';
import 'package:flutterapp/Bean/BeanDirective.dart';
import 'package:flutterapp/DirectiveManager.dart';

import '../SaasManager.dart';

class PageDirectiveEditor extends StatefulWidget {
  static const ROUTER_NAME = "PageDirectiveEditor";

  @override
  _PageDirectiveEditorState createState() => _PageDirectiveEditorState();
}

class _PageDirectiveEditorState extends State<PageDirectiveEditor> {
  List<BeanDirective> listDirective = [];
  String _selectedDirectiveCode = DirectiveManager.DIRECT_LOAD_URI;
  TextEditingController argTextCtrl = new TextEditingController();
  TextEditingController dirLabelCtrl = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("指令管理"),
      ),
      body: Center(
        child: Container(
          child: RefreshIndicator(
              child: ListView.builder(
                  itemCount: listDirective.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Tooltip(
                      child: ListTile(
                        title: Text("${listDirective[index].label}"),
                        trailing: InkWell(
                          child: Icon(Icons.clear),
                          onTap: () {
                            showDelDialog(listDirective[index].label,
                                listDirective[index].objId);
                          },
                        ),
                      ),
                      message: "额外参数为：${listDirective[index].directiveArgs}",
                    );
                  }),
              onRefresh: _onRefresh),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          showAddDialog();
        },
        child: Icon(Icons.add),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
    );
  }

  @override
  void initState() {
    super.initState();
    _onRefresh();
    argTextCtrl.text = '';
    dirLabelCtrl.text = "";
  }

  @override
  void dispose() {
    argTextCtrl.dispose();
    dirLabelCtrl.dispose();
    super.dispose();
  }

  Future<void> _onRefresh() async {
    await SaasManager.getDirectiveList().then((value) {
      listDirective.clear();
      value.forEach((item) {
        listDirective.add(BeanDirective(
            item["label"], item["code"], item["args"], item.objectId));
      });
      setState(() {});
    });
    return;
  }

  void showAddDialog() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("添加指令"),
            content: StatefulBuilder(
              builder: (context, setState) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    DropdownButton(
                      value: _selectedDirectiveCode,
                      items: <DropdownMenuItem<String>>[
                        DropdownMenuItem(
                          value: DirectiveManager.DIRECT_LOAD_URI,
                          child: Text("打开URI"),
                        ),
                        DropdownMenuItem(
                          value: DirectiveManager.DIRECT_OPEN_PKG_NAME,
                          child: Text("打开包名"),
                        )
                      ],
                      onChanged: (val) {
                        setState(() {
                          _selectedDirectiveCode = val;
                        });
                        print("_selectedDirectiveCode $_selectedDirectiveCode");
                      },
                    ),
                    TextField(
                      controller: dirLabelCtrl,
                      decoration: InputDecoration(
//                          contentPadding: EdgeInsets.all(5),
                          hintText: "请输入自定义指令名"),
                    ),
                    TextField(
                      controller: argTextCtrl,
                      decoration: InputDecoration(
//                          contentPadding: EdgeInsets.all(5),
                          hintText: "请输入相关参数"),
                    )
                  ],
                );
              },
            ),
            actions: <Widget>[
              FlatButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('确定'),
                onPressed: () async {
                  if (DirectiveManager.verifyDirective(
                      dirLabelCtrl.text, _selectedDirectiveCode,
                      directiveArgs: argTextCtrl.text)) {
                    Navigator.of(context).pop();
                    await SaasManager.addDirective(
                        dirLabelCtrl.text, _selectedDirectiveCode,
                        directiveArgs: argTextCtrl.text);
                    _onRefresh();
                  }
                },
              ),
            ],
          );
        });
  }

  void showDelDialog(String label, String objId) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("确定删除“$label”"),
            actions: <Widget>[
              FlatButton(
                child: Text('取消'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              FlatButton(
                child: Text('确定'),
                onPressed: () {
                  Navigator.of(context).pop();
                  SaasManager.delDirective(objId).then((value) {
                    _onRefresh();
                  });
                },
              ),
            ],
          );
        });
  }
}
